import pandas as pd
from PySide2.QtCore import QSize, Qt, Slot
from PySide2.QtWidgets import QWidget, QTableWidget, QTableWidgetItem, QTabWidget, QAction, QMessageBox
from forms.uipy.UI_houseVisitRecords import Ui_HouseVisitRecords
from tools.Area_Objects import areaObjs
from tools.Area_tools import Area_Tools
from tools.File_Select_Tools import File_Select_Tools
from server.HouseVisitRecordsServer import HouseVisitRecordsServer
from tools.MatplotlibChartsTools.BarChartTools import BarChartTools


class HouseVisitRecordsForm(QWidget, Ui_HouseVisitRecords):
    def __init__(self):
        super().__init__()
        self.setupUi(self)
        # 初始化下拉选择框数据
        for area in areaObjs[1:]:
            self.area_datas.addItem(area['name'], userData=area['No'])
        self.bindEvent()
        # 总区县数据
        self.total_Bar = BarChartTools()
        # 详细数据
        self.detail_Bar = BarChartTools()

        self.table_show.clear()

        # 绑定下拉选择框事件
        self.area_datas.activated.connect(self.area_selected_changed)

        # 设置表格数据导出到excel中
        self.table_show.setContextMenuPolicy(Qt.ActionsContextMenu)
        send_option = QAction(self.table_show)
        send_option.setText("输出文件")
        send_option.triggered.connect(self.out_file)  # 点击菜单中的“发送控制代码”执行的函数
        self.table_show.addAction(send_option)

    def ok_btn_handle(self):

        # self.showbars.addWidget(self.total_Bar.canvas)
        # self.showbars.addWidget(self.detail_Bar.canvas)

        # 格式化访户记录
        self.format_house_records(self.house_records_path.text())
        # 运行按钮点击
        self.area_id = self.area_datas.currentData()
        self.area_name = self.area_datas.currentText()
        # 访户记录数据
        self.house_data = HouseVisitRecordsServer(self.house_records_path.text(), self.resident_sample_path.text())
        selected = []
        if self.house_data.errorData.get(str(self.area_id)) is None:
            selected = []
        else:
            selected = self.house_data.errorData.get(str(self.area_id))

        area_bar_data = self.house_data.get_area_data(str(self.area_id))
        self.total_Bar.update_data(area_bar_data.get("point"), area_bar_data.get("data"), area_bar_data.get("point"),
                                   self.bar_clicked)
        self.total_Bar.set_title(str(self.house_data.mouth) + "月" + self.area_name + "访户记录汇总情况")
        # 设置访户不足
        self.total_Bar.default_item([i - 1 for i in selected])

        self.showbars.addWidget(self.total_Bar.canvas)
        self.showbars.addWidget(self.detail_Bar.canvas)

        # 显示错误表格
        self.table_show_init()

    def area_selected_changed(self):
        self.area_id = self.area_datas.currentData()
        self.area_name = self.area_datas.currentText()

        selected = []
        if self.house_data.errorData.get(str(self.area_id)) is None:
            selected = []
        else:
            selected = self.house_data.errorData.get(str(self.area_id))

        area_bar_data = self.house_data.get_area_data(str(self.area_id))
        self.total_Bar.update_data(area_bar_data.get("point"), area_bar_data.get("data"), area_bar_data.get("point"),
                                   self.bar_clicked)
        self.total_Bar.set_title(str(self.house_data.mouth) + "月" + self.area_name + "访户记录汇总情况")
        # 设置访户不足
        self.total_Bar.default_item([i - 1 for i in selected])

        # 清空详细点位图
        self.detail_Bar.clear_axes()

        # print(self.area_datas.currentData())

    def table_show_init(self):
        """
        显示表格方法
        :return:
        """
        data = {
            "访户时间为空": self.house_data.get_visit_time_null(),
            "访户时间非当月": self.house_data.get_visit_time_no_current_month(),
            "访问人电话为空": self.house_data.get_visitor_phone_null(),
            "无效访问": self.house_data.get_error_visit()
        }
        self.data_df = {}
        for key in data.keys():
            self.data_df[key] = data[key]
            # 空数据不显示
            if len(data[key]) == 0:
                continue
            table = QTableWidget()
            # 设置行数和列宽
            table.setRowCount(len(data[key]))
            table.setColumnCount(len(data[key].keys()))
            table.setHorizontalHeaderLabels(list(data[key].keys()))
            for i, row in data[key].iterrows():
                for j in range(len(row)):
                    # 设置数据
                    table.setItem(i, j, QTableWidgetItem(str(row[j])))
            self.table_show.addTab(table, key)

    def bindEvent(self):
        self.house_records_btn.clicked.connect(
            lambda:
            self.house_records_path.setText(File_Select_Tools.select_one_file(title="访户记录")[0])
        )
        self.resident_sample_btn.clicked.connect(
            lambda: self.resident_sample_path.setText(File_Select_Tools.select_one_file(title="住户样本")[0]))
        self.ok_run.clicked.connect(self.ok_btn_handle)

        # HouseVisitRecordsServer(self.house_records_path.text(),self.resident_sample_path.text())

    def bar_clicked(self, event):
        i = self.total_Bar.clicked_item_category(event)
        area_bar_data = self.house_data.get_area_and_points(self.area_id, i)
        self.detail_Bar.update_data(area_bar_data.get("houseID"), area_bar_data.get("data"))
        self.detail_Bar.set_title(str(self.house_data.mouth) + "月" + self.area_name + str(i) + "点访户记录数量")

    def format_house_records(self, path):
        # 读取数据
        with open(path, 'r') as f:
            content = f.read()
        content = content.replace('\n,', ',')
        content = content.replace(',\n', ',')
        with open(path, 'w') as f:
            f.write(content)

    # @Slot
    def out_file(self):
        """
        将表格数据输出到指定文件夹
        :return:
        """
        file_dir = File_Select_Tools.select_dir(title="输出文件夹")
        with pd.ExcelWriter(f"{file_dir}/访户记录审核数据.xlsx") as writer:
            for key in self.data_df.keys():
                if len(self.data_df[key]) != 0:
                    self.data_df[key].to_excel(writer, sheet_name=key, index=False)

        QMessageBox.information(None, '提示', '导出完成')
        pass
